var fs = require('fs');
var util = require('./index');

var logFile = null;

var level = {
	0:'Info',
	1:'Warn',
	2:'Error'
};

var tpl = '[{0}]({1}) {2}--{3}';
var tpl2 = '[{0}] {1}--{2}';

var format = function(str, arr){
	str = str.replace(/({(\d+)})/g,function($0,$1,$2){
		return arr[$2] || '';
	});
	return str;
};

var formatDate = function(date){
	return format('{0}-{1}-{2} {3}:{4}:{5}',[date.getFullYear(), date.getMonth()+1, date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds()]);
};

exports.release = function(){
	if(logFile != null){
		logFile.end();
		logFile = null;
	}
};

exports.log = function(str, lv, tag){
	lv = lv || 0;
	tag = tag || '';
	var now = new Date();
	if(typeof str == 'object'){
		str = JSON.stringify(str);
	}
	var text;
	if(tag){
		text = format(tpl,[level[lv],tag, formatDate(now), str]);
	}else{
		text = format(tpl2,[level[lv], formatDate(now), str]);
	}
	console.log(text);
	if(logFile == null){
		var file = format("{0}{1}{2}-{3}{4}{5}", [now.getFullYear(), now.getMonth()+1, now.getDate(), now.getHours(), now.getMinutes(), now.getSeconds()]);
		logFile = fs.createWriteStream(util.getWorkingPath("./cache/log/log"+file+".log"));
	}
	logFile.write(text+"\n");
};

exports.logs = function(str, arr, lv, tag){
	exports.log(format(str,arr),lv, tag);
};

exports.i = function(str, tag){
	exports.log(str, 0, tag);
};

exports.e = function (str, tag) {
	exports.log(str, 2, tag);
};